//
//  PFCycleImages.m
//  16-UICollectionViewImage
//
//  Created by dllo on 16/8/4.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PFCycleImages.h"
#define kCollectionViewCellReuse @"reuse"

@interface PFCycleImages ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong)UICollectionView *cycleCollectionView;
@property (nonatomic, strong)UIPageControl *pageControl;
@property (nonatomic, strong)UILabel *titleLabel;
@end

@implementation PFCycleImages

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
    }
    return self;
}

- (void)setUp {
    [self createCollectionView];
    [self createPageControll];
    [self createTitleLabel];
    [self addTimer];
    
}
- (void)createCollectionView {
    _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;
    
    _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_flowLayout];
    
    _cycleCollectionView.delegate = self;
    _cycleCollectionView.dataSource = self;
    _cycleCollectionView.pagingEnabled = YES;
    [self addSubview:_cycleCollectionView];
    [_cycleCollectionView registerClass:[PFCycleImagesCell class] forCellWithReuseIdentifier:kCollectionViewCellReuse];
    
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _array.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PFCycleImagesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellReuse forIndexPath:indexPath];
    
//    cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1];
//    cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(handleDataWithObject:cell:)]) {
        [self.dataSource handleDataWithObject:_array[indexPath.row] cell:cell];
    }
    return cell;
}

- (void)createPageControll {
    _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
    [self addSubview:_pageControl];
    
}
- (void)createTitleLabel {
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _titleLabel.backgroundColor = [UIColor redColor];
    [self addSubview:_titleLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSLog(@"%lf", self.frame.size.width);
    _cycleCollectionView.frame = self.bounds;
    _flowLayout.itemSize = self.bounds.size;
    [_cycleCollectionView setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    _pageControl.frame = CGRectMake(0, _cycleCollectionView.frame.size.height - 50, self.bounds.size.width, 50);
    _pageControl.numberOfPages = _array.count - 2;
    [_pageControl setCurrentPage:0];
    [_pageControl addTarget:self action:@selector(pageControlValueChange:) forControlEvents:UIControlEventValueChanged];
    _titleLabel.frame = CGRectMake(0, 20, _cycleCollectionView.bounds.size.width, 30);
}
- (void)pageControlValueChange:(UIPageControl *)pageControll {
    NSInteger page = _pageControl.currentPage;
    _cycleCollectionView.contentOffset = CGPointMake((page + 1) * _cycleCollectionView.bounds.size.width, 0);
    _titleLabel.text = _titleArray[_pageControl.currentPage];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
   //  直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
//        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width * (_array.count - 2), 0)];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        [_pageControl setCurrentPage:_array.count - 3];
        
        
    } else if (scrollView.contentOffset.x == _cycleCollectionView.bounds.size.width * (_array.count - 1)) {
//        [_cycleCollectionView setContentOffset:CGPointMake(_cycleCollectionView.bounds.size.width , 0)];
        [_pageControl setCurrentPage:0];
        [_cycleCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        
    } else {
        _pageControl.currentPage = (_cycleCollectionView.contentOffset.x / _cycleCollectionView.bounds.size.width) - 1;
    }
    _titleLabel.text = _titleArray[_pageControl.currentPage];
}

- (void)setArray:(NSArray *)array {
    _array = array;
    [_cycleCollectionView reloadData];
}
- (void)setTitleArray:(NSArray *)titleArray {
    _titleArray = titleArray;
}
// 开启定时器
- (void)addTimer {
    //  仅仅是创建一个timer， 并没有加在loop中
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
//    创建一个timer， 并添加在loop中
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    
//NSDefaultRunLoopMode 和 NSRunLoopCommonModes
//    前者代表默认状态， scheduledTimerWithTimeInterval 添加为默认状态
//    后者为多种状态， 包含 默认 及 滚动 状态
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)nextImage {
    NSInteger page =_cycleCollectionView.contentOffset.x / _cycleCollectionView.bounds.size.width;
    
    if (page == 0) {
        page = _array.count - 2;
    } else if (page == _array.count - 2) {
        page = 1;
    } else {
        page++;
        
    }
    _pageControl.currentPage = page - 1;
    _titleLabel.text = _titleArray[_pageControl.currentPage];
    CGFloat x = page  * _cycleCollectionView.bounds.size.width;
    _cycleCollectionView.contentOffset = CGPointMake(x, 0);
}


// 关闭定时器
- (void)removeTimer {
    //取消timer
    [self.timer invalidate];
    //timer置空
    self.timer = nil;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    关闭定时器
    [self removeTimer];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//   开启定时器
    [self addTimer];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

@implementation PFCycleImagesCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
    }
    return self;
}

@end






